import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hack_a_tone/bloc/apps_keeper.dart';
import 'package:hack_a_tone/bloc/background_keeper.dart';
import 'package:hack_a_tone/bloc/jira_service.dart';
import 'package:multi_select_flutter/multi_select_flutter.dart';

class ZenRecorderScreen extends StatefulWidget {
  const ZenRecorderScreen({super.key});
  @override
  State<ZenRecorderScreen> createState() => _ZenRecorderScreenState();
}

class _ZenRecorderScreenState extends State<ZenRecorderScreen> {
  bool isRecording = false;

  Map<String, String> tasks = {};
  String? selectedTask = "YAPTAT";
  List<String> selectedOptions = [];
  List<String> options = [];
  String formatDuration(Duration duration) {
    final hours = duration.inHours.toString().padLeft(2, '0');
    final minutes = (duration.inMinutes % 60).toString().padLeft(2, '0');
    final seconds = (duration.inSeconds % 60).toString().padLeft(2, '0');
    return '$hours:$minutes:$seconds';
  }

  Timeline focusTimeline = {};
  Timeline allTimeline = {};
  @override
  void initState() {
    super.initState();
    BlocProvider.of<BackWindowKeeperBloc>(context)
        .add(StartTrackingBackWindows());
    tasks = BlocProvider.of<JiraCubit>(context).state.$4;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('YAPTAT'),
      ),
      body: Center(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          // const EdgeInsets.only(
          //         top: 200, bottom: 20, left: 40, right: 40),

          children: [
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 50.0),
              child: BlocBuilder<ActiveWindowKeeperBloc, TimerState>(
                  buildWhen: (f, s) {
                return f != s;
              }, builder: (context, state) {
                final commonDur =
                    selectedOptions.fold<Duration>(Duration.zero, (dura, str) {
                  if (state.apps.containsKey(str)) {
                    return state.apps[str]!.fold<Duration>(
                        dura,
                        (previousValue, element) =>
                            element.duration + previousValue);
                  }
                  return dura;
                });
                return Text(
                  formatDuration(commonDur),
                  style: const TextStyle(fontSize: 38),
                );
              }),
            ),
            IconButton.filledTonal(
                iconSize: 58,
                onPressed: () async {
                  if (isRecording) {
                    BlocProvider.of<ActiveWindowKeeperBloc>(context)
                        .add(StopTrackingActiveWindow());

                    final commonDur = selectedOptions
                        .fold<Duration>(Duration.zero, (dura, str) {
                      if (BlocProvider.of<ActiveWindowKeeperBloc>(context)
                          .state
                          .apps
                          .containsKey(str)) {
                        return BlocProvider.of<ActiveWindowKeeperBloc>(context)
                            .state
                            .apps[str]!
                            .fold<Duration>(
                                dura,
                                (previousValue, element) =>
                                    element.duration + previousValue);
                      }
                      return dura;
                    });
                    BlocProvider.of<JiraCubit>(context)
                        .timeLeft(commonDur, selectedTask!);
                  } else {
                    BlocProvider.of<ActiveWindowKeeperBloc>(context)
                        .add(StartTrackingActiveWindow());
                  }
                  setState(() {
                    isRecording = !isRecording;
                  });
                },
                icon: (!isRecording
                    ? const Icon(Icons.play_arrow)
                    : const Icon(Icons.stop))),
            // Text(ProgramUtils.mergeData(focusTimeline, allTimeline).toString()),
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 50.0),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  IconButton(
                      onPressed: () {
                        setState(() {
                          options =
                              BlocProvider.of<BackWindowKeeperBloc>(context)
                                  .state
                                  .apps
                                  .keys
                                  .toList();
                        });
                      },
                      icon: const Icon(Icons.refresh)),
                  SizedBox(
                    width: 200,
                    child: MultiSelectDialogField(
                      items: options.map((e) => MultiSelectItem(e, e)).toList(),
                      listType: MultiSelectListType.CHIP,
                      onConfirm: (values) {
                        selectedOptions = values;
                      },
                    ),
                  )
                ],
              ),
            ),

            DropdownMenu<String>(
              onSelected: (value) {
                selectedTask = value;
              },
              dropdownMenuEntries: tasks.entries
                  .map(
                      (kv) => DropdownMenuEntry(label: kv.value, value: kv.key))
                  .toList(),
            )
          ],
        ),
      ),
    );
  }
}
